package com.heima.comment.listener;

import com.heima.common.constants.ArticleConstants;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class CommentListener {

    @Autowired
    private MongoTemplate mongoTemplate;

    //监听关闭评论 删除评论
    @KafkaListener(topics = ArticleConstants.ARTICLE_COMMENT_STATUS)
    public void onMessage(String message){
        Long articleId = Long.valueOf(message);
        //获取评论的id集合
        List<String> commentIdList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(articleId)), ApComment.class).
                stream().map(ApComment::getId).collect(Collectors.toList());
        for (String commentId : commentIdList) {
            //删除评论的点赞
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)), ApCommentLike.class);

            //ApComment apComment = mongoTemplate.findById(commentId,ApComment.class);
            //回复的集合
            List<String> commentRepayIdList = mongoTemplate.find(Query.query(Criteria.where("commentId").is(commentId)),
                            ApCommentRepay.class).stream().map(ApCommentRepay::getId).collect(Collectors.toList());
            //删除回复的点赞
            for (String commentRepayId : commentRepayIdList) {
                mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentRepayId)),ApCommentLike.class);
            }
            //删除回复
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)), ApCommentRepay.class);
            //删除评论
            mongoTemplate.remove(Query.query(Criteria.where("id").is(commentId)),ApComment.class);

        }
    }
}
